package com.sky.service.impl;

import com.alibaba.fastjson.JSONObject;
import com.sky.constant.MessageConstant;
import com.sky.context.BaseContext;
import com.sky.dto.OrdersPaymentDTO;
import com.sky.dto.OrdersSubmitDTO;
import com.sky.entity.AddressBook;
import com.sky.entity.OrderDetail;
import com.sky.entity.Orders;
import com.sky.entity.User;
import com.sky.exception.BaseException;
import com.sky.exception.OrderBusinessException;
import com.sky.mapper.OrderDetailMapper;
import com.sky.mapper.OrdersMapper;
import com.sky.mapper.UserMapper;
import com.sky.service.AddressBookService;
import com.sky.service.OrderService;
import com.sky.service.ShoppingCartService;
import com.sky.service.UserService;
import com.sky.utils.WeChatPayUtil;
import com.sky.vo.OrderPaymentVO;
import com.sky.vo.OrderSubmitVO;
import com.sky.vo.ShoppingCartVO;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;

import java.math.BigDecimal;
import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.List;
import java.util.UUID;

@Service
public class OrderServiceImpl implements OrderService {

    @Autowired
    private AddressBookService addressBookService;
    @Autowired
    private ShoppingCartService cartService;
    @Autowired
    private UserService userService;
    @Autowired
    private OrdersMapper ordersMapper;
    @Autowired
    private OrderDetailMapper detailMapper;


    @Override
    @Transactional(rollbackFor = Exception.class)
    public OrderSubmitVO subimt(OrdersSubmitDTO dto) {
        // addressBookId查询收货地址
        AddressBook addressBook = addressBookService.getById(dto.getAddressBookId());
        if(addressBook == null){
            throw new BaseException(MessageConstant.ADDRESS_BOOK_IS_NULL);
        }
        // 查询我的购物车，得到菜品或者套餐数据
        List<ShoppingCartVO> cartList = cartService.list();
        if(CollectionUtils.isEmpty(cartList)){
            throw new BaseException(MessageConstant.SHOPPING_CART_IS_NULL);
        }
        // 查询用户信息
        User user = userService.getById(BaseContext.getCurrentId());
        if(user == null){
            throw new BaseException(MessageConstant.USER_NOT_EXISTS);
        }
        // 生成订单
        // insert orders
        Orders orders = new Orders();
        BeanUtils.copyProperties(dto, orders);
        orders.setNumber(UUID.randomUUID().toString());
        orders.setStatus(Orders.PENDING_PAYMENT);
        orders.setUserId(BaseContext.getCurrentId());
        orders.setUserName(user.getName());
        orders.setOrderTime(LocalDateTime.now());
        orders.setPayStatus(Orders.UN_PAID);
        orders.setPhone(addressBook.getPhone());
        orders.setAddress(addressBook.getProvinceName()+addressBook.getCityName()+addressBook.getDistrictName()+addressBook.getDetail());
        orders.setConsignee(addressBook.getConsignee());
        ordersMapper.insert(orders);
        // insert order_detail
        List<OrderDetail> orderDetails = new ArrayList<>();
        for (ShoppingCartVO shoppingCartVO : cartList) {
            OrderDetail detail = new OrderDetail();
            BeanUtils.copyProperties(shoppingCartVO, detail);
            detail.setId(null);
            detail.setOrderId(orders.getId());
            orderDetails.add(detail);
        }
        detailMapper.insertBatch(orderDetails);
        // 清空购物车
        cartService.clean();
        // 构造返回
        OrderSubmitVO vo = new OrderSubmitVO();
        vo.setId(orders.getId());
        vo.setOrderTime(orders.getOrderTime());
        vo.setOrderAmount(orders.getAmount());
        vo.setOrderNumber(orders.getNumber());
        return vo;
    }
    @Autowired
    private UserMapper userMapper;
    @Autowired
    private WeChatPayUtil weChatPayUtil;

    /**
     * 订单支付
     *
     * @param ordersPaymentDTO
     * @return
     */
    @Override
    public OrderPaymentVO payment(OrdersPaymentDTO ordersPaymentDTO) throws Exception {
        // 当前登录用户id
        Long userId = BaseContext.getCurrentId();
        User user = userMapper.selectById(userId);

        //调用微信支付接口，生成预支付交易单
        JSONObject jsonObject = weChatPayUtil.pay(
                ordersPaymentDTO.getOrderNumber(), //商户订单号
                new BigDecimal(0.01), //支付金额，单位 元
                "苍穹外卖订单", //商品描述
                user.getOpenid() //微信用户的openid
        );

        if (jsonObject.getString("code") != null && jsonObject.getString("code").equals("ORDERPAID")) {
            throw new OrderBusinessException("该订单已支付");
        }

        OrderPaymentVO vo = jsonObject.toJavaObject(OrderPaymentVO.class);
        vo.setPackageStr(jsonObject.getString("package"));

        return vo;
    }
    /**
     * 支付成功，修改订单状态
     *
     * @param outTradeNo
     */
    @Override
    public void paySuccess(String outTradeNo) {
        // 根据订单号查询当前用户的订单
        Orders ordersDB = ordersMapper.selectByOrderNumber(outTradeNo);
        // 根据订单id更新订单的状态、支付方式、支付状态、结账时间
        Orders orders = Orders.builder()
                .id(ordersDB.getId())
                .status(Orders.TO_BE_CONFIRMED)
                .payStatus(Orders.PAID)
                .checkoutTime(LocalDateTime.now())
                .build();
        ordersMapper.update(orders);
    }
}
